import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { metaObj, publicMeta } from './meta'
type Page = { [props in string]: () => Promise<any> }
const pages: Page = import.meta.glob([
  '@/pages/**/*.vue',
  '!@/pages/**/component*/**/*.vue',
])
let indexPage = ''
let indexRoute: RouteRecordRaw = {
  path: '/',
  name: '/',
  redirect: '/',
}
const routes = Object.keys(pages)?.map((p: string): RouteRecordRaw => {
  const paths = /pages\/(.*)\/(.*).vue/.exec(p) as string[]
  let path
  if (paths[2] === 'index') {
    path = `/${paths[1]}`
  } else {
    path = `/${paths[1]}/${paths[2]}`
  }
  const name = metaObj[path]?.name || path
  if (!indexPage) {
    indexPage = name
    indexRoute = {
      path: '/',
      name,
      component: pages[p],
      meta: { ...publicMeta, ...metaObj[path] },
    }
  }
  return {
    path,
    name,
    component: pages[p],
    meta: { ...publicMeta, ...metaObj[path] },
  }
})
routes.push(indexRoute)
routes.push({
  name: 'notFound',
  path: '/:path(.*)+',
  redirect: {
    name: '/404',
  },
})
console.log('routes:', routes)
const router = createRouter({
  routes,
  history: createWebHashHistory(import.meta.env.BASE_URL),
})
router.beforeEach((to, from, next) => {
  console.debug(to, from)
  const title = to?.meta?.title
  if (title) {
    document.title = title as string
  }
  next()
})

export default router
